package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Spot;
import cn.wolfcode.wolf2w.query.SpotQuery;
import cn.wolfcode.wolf2w.repository.SpotRepository;
import cn.wolfcode.wolf2w.service.ISpotService;
import cn.wolfcode.wolf2w.util.PageHelperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by 甘静斌 on 2020-08-07 13:41
 */
@Service
//@Transactional
public class SpotServiceImpl implements ISpotService {

    @Autowired
    private SpotRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(Spot spot) {
        spot.setId(null);
        repository.save(spot);
    }

    @Override
    public void update(Spot spot) {

        repository.save(spot);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Spot get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Spot> list() {


        return repository.findAll();
    }

    @Override
    public Page<Spot> query(SpotQuery qo) {

        //查询封装类
        Query query = new Query();

        //分页数据 , currentPage , pageSite
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize() ,Sort.Direction.ASC,"_id");

        Page<Spot> page = PageHelperUtil.query(template, pageable, Spot.class, query, qo);
        //list Pageable total 封装三个数据,返回给页面
        return page;
    }

    @Override
    public void saveOrUpdate(Spot spot) {

        //update
        //mongodb - repository 的更新操作时全量更新
        //为什么此处操作没有出现参数丢失问题
        //spot 编辑时页面修改数据个数刚好跟表中列个数一致
        //即全量修改
        if (StringUtils.hasLength(spot.getId())){

            this.update(spot);
        }else {
            this.save(spot);
        }
    }

 

    


}
